<% layout('/layouts/default.html', {title: '收款选择', libs: ['validate','dataGrid']}){ %>
<div class="main-content">
    <div class="box box-main">
        <div class="box box-main" >
            <div class="box-header with-border">
                <div class="box-title">
                    <i class="fa icon-notebook"></i> ${text('收款选择')}
                </div>
                <div class="box-tools pull-right">

                </div>
            </div>
            <#form:form id="inputForm"  model="${treceivable}" action="${ctx}/arecieve/treceivable/save" method="post" class="form-horizontal">
            <div class="box-body">
                <div class="col-xs-6">
                    <#form:hidden path="receivableId"/>
                    <div class="form-group">
                        <label class="control-label col-sm-4" title="">
                            <span class="required hide">*</span> ${text('编号')}：<i class="fa icon-question hide"></i></label>
                        <div class="col-sm-8">
                            <#form:input path="receivableCode" dictType="" class="form-control" readOnly="true" placeholder="自动生成"/>
                        </div>
                    </div>
                </div>
                <div class="col-xs-6">
                    <div class="form-group " >
                        <label class="control-label col-sm-4" title="">
                            <span class="required">*</span> ${text('客户')}：<i class="fa icon-question hide"></i></label>
                        <div class="col-sm-8">
                            <#form:select path="customerId" items="${customerList}" itemLabel="customerName" itemValue="customerId"  class="form-control required" />
                        </div>
                    </div>
                </div>
                <div class="col-xs-6">
                    <div class="form-group">
                        <label class="control-label col-sm-4" title="">
                            <span class="required ">*</span> ${text('日期')}：<i class="fa icon-question hide"></i></label>
                        <div class="col-sm-8">
                            <#form:input path="date" readonly="true"  maxlength="20" class="form-control laydate required"
                            dataFormat="date" data-type="date" data-format="yyyy-MM-dd"/>
                        </div>
                    </div>
                </div>
                <div class="col-xs-6">
                    <div class="form-group">
                        <label class="control-label col-sm-4" title="">
                            <span class="required">*</span> ${text('服务订单')}：<i class="fa icon-question hide"></i></label>
                        <div class="col-sm-8">
                            <#form:select path="serviceOrderId"  items="${serviceOrderList}" itemLabel="serviceOrderCode" itemValue="serviceOrderId" class="form-control required" />
                        </div>
                    </div>
                </div>
                <div class="col-xs-6">
                    <div class="form-group">
                        <label class="control-label col-sm-4" title="">
                            <span class="required hide">*</span> ${text('应收单')}：<i class="fa icon-question hide"></i></label>
                        <div class="col-sm-8">
                            <#form:select path="arCode" items="${tarList}" itemLabel="arCode" itemValue="arId" dictType="" blankOption="true" class="form-control" />
                        </div>
                    </div>
                </div>
                <div class="col-xs-6">
                    <div class="form-group">
                        <label class="control-label col-sm-4" title="">
                            <span class="required ">*</span> ${text('收款/核销金额')}：<i class="fa icon-question hide"></i></label>
                        <div class="col-sm-8">
                            <#form:input path="receivableAmount" class="form-control required number" readonly="true"/>
                        </div>
                    </div>
                </div>
                <div class="col-xs-6">
                    <div class="form-group">
                        <label class="control-label col-sm-4" title="">
                            <span class="required ">*</span> ${text('币种')}：<i class="fa icon-question hide"></i></label>
                        <div class="col-sm-8">
                            <#form:select path="currency" dictType="sys_bizhongy" class="form-control required" />
                        </div>
                    </div>
                </div>
                <div class="col-xs-6">
                    <div class="form-group">
                        <label class="control-label col-sm-4" title="">
                            <span class="required ">*</span> ${text('收款方式')}：<i class="fa icon-question hide"></i></label>
                        <div class="col-sm-8">
                            <#form:select path="receivableMethod" dictType="pay_type" class="form-control required" />
                        </div>
                    </div>
                </div>
                <div class="col-xs-6">
                    <div class="form-group">
                        <label class="control-label col-sm-4" title="">
                            <span class="required hide">*</span> ${text('收款银行')}：<i class="fa icon-question hide"></i></label>
                        <div class="col-sm-8">
                            <#form:select path="receivableBank"  items="${taccountList}" itemLabel="accountName" itemValue="accountId" blankOption="true" class="form-control" />
                        </div>
                    </div>
                </div>
                <div class="row">
                    <div class="col-xs-12">
                        <div class="form-group">
                            <label class="control-label col-sm-2" title="">
                                <span class="required hide">*</span> ${text('备注信息')}：<i class="fa icon-question hide"></i></label>
                            <div class="col-sm-10">
                                <#form:textarea path="remarks" rows="4" maxlength="500" class="form-control"/>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="row">
                    <div class="col-xs-12">
                        <div class="form-group">
                            <label class="control-label col-sm-2" title="">
                                <span class="required hide">*</span><i class="fa icon-question hide"></i></label>
                            <div class="col-sm-10">
                                <#form:checkbox path="replaceFile" label="是否核销" class="form-control"/>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="row" style="margin-left: 400px;">
                <div class="form-group">
                    <button type="button" class="btn btn-primary btn-sm" onclick="getPaidInfo()">${text('查询')}</button>

                </div>
                </div>
                <h4 class="form-unit">${text('应收单明细')}</h4>
                <div class="ml10 mr10">
                    <table id="paidGrid"></table>
                </div>
                <h4 class="form-unit">${text('系统信息')}</h4>
                <div class="col-xs-6">
                    <div class="form-group">
                        <label class="control-label col-sm-4" title="">
                            <span class="required hide">*</span> ${text('创建者')}：<i class="fa icon-question hide"></i></label>
                        <div class="col-sm-8">
                            <#form:input path="createBy" maxlength="64" class="form-control" disabled="true"/>
                        </div>
                    </div>
                </div>
                <div class="col-xs-6">
                    <div class="form-group">
                        <label class="control-label col-sm-4" title="">
                            <span class="required hide">*</span> ${text('创建时间')}：<i class="fa icon-question hide"></i></label>
                        <div class="col-sm-8">
                            <#form:input path="createDate" readonly="true" maxlength="20" class="form-control" disabled="true"
                            dataFormat="date" data-type="date" data-format="yyyy-MM-dd"/>
                        </div>
                    </div>
                </div>
                <div class="col-xs-6">
                    <div class="form-group">
                        <label class="control-label col-sm-4" title="">
                            <span class="required hide">*</span> ${text('更新者')}：<i class="fa icon-question hide"></i></label>
                        <div class="col-sm-8">
                            <#form:input path="updateBy" maxlength="64" class="form-control" disabled="true"/>
                        </div>
                    </div>
                </div>
                <div class="col-xs-6">
                    <div class="form-group">
                        <label class="control-label col-sm-4" title="">
                            <span class="required hide">*</span> ${text('更新时间')}：<i class="fa icon-question hide"></i></label>
                        <div class="col-sm-8">
                            <#form:input path="updateDate" readonly="true" maxlength="20" class="form-control" disabled="true"
                            dataFormat="date" data-type="date" data-format="yyyy-MM-dd"/>
                        </div>
                    </div>
                </div>
                <div class="box-footer">
                    <div class="row">
                        <div class="col-sm-offset-2 col-sm-10">
                            <% if (hasPermi('arecieve:treceivable:edit')){ %>
                            <button type="submit" class="btn btn-sm btn-primary" id="btnSubmit"><i class="fa fa-check"></i> ${text('保 存')}</button>&nbsp;
                            <% } %>
                            <button type="button" class="btn btn-sm btn-default" id="btnCancel" onclick="js.closeCurrentTabPage()"><i class="fa fa-reply-all"></i> ${text('关 闭')}</button>
                        </div>
                    </div>
                </div>
            </#form:form>

        </div>
    </div>
</div>
<% } %>
<script>
    // 初始化DataGrid对象
    $('#paidGrid').dataGrid({
        datatype: "local", // 设置本地数据
        autoGridHeight: function(){return 'auto'}, // 设置自动高度

        columnModel: [
            {header:'状态', name:'status', editable:true, hidden:true},
            {header:'主键', name:'receivableDetailId', editable:true, hidden:true},
            {header:'${text("应收单编号")}', name:'arCode', width:150, editable:true, edittype:'text', editoptions:{'maxlength':'100', 'class':'form-control','readonly':'true'}},
            {header:'${text("行号")}', name:'rowNumber', width:150, editable:true, edittype:'text', editoptions:{'maxlength':'100', 'class':'form-control','readonly':'true'}},
            {header:'${text("品牌")}', name:'brand', width:150, editable:true, edittype:'select', editoptions:{'maxlength':'2', 'class':'form-control','readonly':'true',
                    items: $.merge([{dictLabel:'&nbsp;',dictValue:''}], ${@DictUtils.getDictListJson('car_pinpai')}),
                    itemLabel: 'dictLabel', itemValue: 'dictValue'
            }},
            {header:'${text("版型")}', name:'area', width:150, editable:true, edittype:'select', editoptions:{'maxlength':'64', 'class':'form-control','readonly':'true',
                    items: $.merge([{dictLabel:'&nbsp;',dictValue:''}], ${@DictUtils.getDictListJson('car_quyu')}),
                    itemLabel: 'dictLabel', itemValue: 'dictValue'
                }},
            {header:'${text("车型")}', name:'model', width:150, editable:true, edittype:'text', editoptions:{'maxlength':'100', 'class':'form-control','readonly':'true'}},
            {header:'${text("车辆")}', name:'carId', width:150, editable:true, hidden:true, edittype:'text', editoptions:{'maxlength':'64', 'class':'form-control','readonly':'true'}},
            {header:'${text("车辆")}', name:'tcar.carName', width:150,  edittype:'text',  editable:true, editoptions:{'maxlength':'64', 'class':'form-control','readonly':'true'}},
            {header:'${text("车架号")}', name:'frameNumber', width:150, editable:true, edittype:'text', editoptions:{'maxlength':'100', 'class':'form-control','readonly':'true'}},
            {header:'${text("费用项目")}', name:'fixedExpense.fixedExpenseName', width:150, editable:true, edittype:'text', editoptions:{'class':'form-control','readonly':'true'}},
            {header:'${text("项目")}', name:'expenseItem', width:150, editable:true, edittype:'text', hidden:true, editoptions:{'class':'form-control','readonly':'true'}},
            {header:'${text("应收金额")}', name:'arAmount', width:150, editable:true, edittype:'text', editoptions:{'class':'form-control required number','readonly':'true'}},
            {header:'${text("实收金额")}', name:'actualArAmount', width:150, editable:true, edittype:'text', editoptions:{'class':'form-control number'}},
            {header:'${text("剩余应收金额")}', name:'receivedLeft', width:150,edittype:'text',  editable:true, editoptions:{'class':'form-control number','readonly':'true'}},
            {header:'${text("开票金额")}', name:'invoiceAmount', width:150, editable:true, edittype:'text', editoptions:{'class':'form-control number','readonly':'true'}},
            {header:'${text("备注")}', name:'remarik', width:150, editable:true, edittype:'text', editoptions:{'maxlength':'255', 'class':'form-control','readonly':'true'}},
            {header:'${text("收款单ID")}', name:'receivableId.receivableId', editable:true, hidden:true},
            {header:'${text("预收款")}', name:'advancesReceivedCode1', edittype:'text',editable:true, hidden:true},
            {header:'${text("预收款编号")}', name:'advancesReceivedCode', width:250,  edittype:'select', editable:true,  editoptions:{'class':'form-control',
                    dataInit: function(element){
                        $(element).select2().on("change",function(){
                            var value =$(this).val();
                            var number=$(this).closest('tr').find("input[name=\"rowNumber\"]").val();
                            var type=$(this).closest('tr').find("input[name=\"expenseItem\"]").val();

                            var that =$(this)
                            $.ajax({
                                type: "POST",
                                async : false,
                                url: "${ctx}/prerecieve/tadvancesReceived/findLeftMoney",
                                data: {number: number,value:value,type:type},
                                success: function (data) {
                                    if(data!=null&&data!=""){
                                        that.closest('tr').find("input[name=\"receivedBalance\"]").val(data);
                                        that.closest('tr').find("input[name=\"advancesReceivedCode1\"]").val(value);
                                    }
                                }
                            });
                        });
                    }
                }},
            {header:'${text("预收款余额")}', name:'receivedBalance', width:150,  edittype:'text', editable:true,  editoptions:{'class':'form-control number','readonly':'true'}},

        ],

        editGrid: true,				// 是否是编辑表格
        editGridInitRowNum: 0,		// 编辑表格的初始化新增行数
        // 编辑表格的提交数据参数
        editGridInputFormListName: 'treceivableDetailList', // 提交的数据列表名
        editGridInputFormListAttrs: 'status,arCode,arDetailId,rowNumber,brand,area,model,carId,frameNumber,expenseItem,apAmount,actualApAmount,remarik,arId.arId,', // 提交数据列表的属性字段

        // 加载成功后执行事件
        ajaxSuccess: function(data){

        }
    });

    $("#inputForm").validate({
        submitHandler: function(form){
            js.ajaxSubmitForm($(form), function(data){
                js.showMessage(data.message);
                if(data.result == Global.TRUE){
                    js.closeCurrentTabPage(function(contentWindow){
                        contentWindow.page();
                    });
                }
            }, "json");
        }
    });

    //查询
    function getPaidInfo() {
        var h1 =$("#customerId").val();
        var h2 =$("form").find("#arCode").val();
        var h3 =$("#serviceOrderId").val();

        if(h1==null||h1==""){
            js.showMessage("客户不能为空");
            return;
        }
        var data ={"customerId":h1,"serviceOrderId":h3,"arId":h2}

        $.ajax({
            type: "post",
            //获取应收列表
            url: "${ctx}/ar/tar/getTarList",
            data: data,
            dataType: "json",
            success: function(data){

                $('#paidGrid').jqGrid('clearGridData');　　　　//先清空，再加载
                $("#paidGrid").jqGrid('setGridParam', {
                    datatype:"local",
                    data:data　　           //result为ajax请求成功后后台返回的products
                }).trigger("reloadGrid");
                getPre()
            }

        });
    }
        //提交
        /*$(function () {

            $("#date").attr("value",js.formatDate(new Date()
                , 'yyyy-MM-dd'));

            $("#btnSubmit").click(function () {
                var list =$("td[aria-describedby=\"paidGrid_arDetailId\"]")
                var str=""
                list.each(function () {
                    str=str+$(this).attr("title")+",";
                })
                var customerId =$("#customerId").val();
                var date =$("#date").val();
                var serviceOrderId =$("#serviceOrderId").val();
                var currency =$("#currency").val();
                var receivableMethod =$("#receivableMethod").val();
                var receivableBank =$("#receivableBank").val();
                location.href="${ctx}/arecieve/treceivable/saveAll?str="+str+"&customerId="+customerId+"&date="+date+"&serviceOrderId="+serviceOrderId+"&currency="+currency+"&receivableMethod="+receivableMethod+"&receivableBank="+receivableBank
            })
        })*/

    //费用项目
/*    $(function () {
        var str="";
        $.ajax({
            type: "POST",
            async : false,
            url: "${ctx}/payment/tap/getExpenseItem",
            // data: {"serviceOrderId": $("#serviceOrderId").val()},
            dataType : "json",
            success: function (data) {
                // $('#currency').select2('val', data.currency);
                //根据订单编号赋值
                if (data.length > 0) {
                    for (var i = 0; i < data.length; i++) {
                        var frameNumber1 = data[i].fixedExpenseName;

                        var frameNumberId = data[i].fixedExpenseId;
                        if(i!=data.length-1){
                            str+=frameNumberId+":"+frameNumber1+";";
                        }else {
                            str+=frameNumberId+":"+frameNumber1;// 这里是option里面的 value:label
                        }
                    }

                } else{
                    js.showErrorMessage("该订单没有车架号信息！");
                }
                $('#paidGrid').setColProp('expenseItem', {editoptions: {value:str}});
                $('#paidGrid').dataGrid('reloadGrid');

            }
        });

    })*/
    $(function () {
        $("table[id=\"paidGrid\"]").on("blur", "input[name=\"actualArAmount\"]", function () {
            var money = 0;
            $("input[name=\"actualArAmount\"]").each(function () {
                if ($(this).val() != NaN && $(this).val() != null && $(this).val() != "") {
                    money = money + parseInt($(this).val());
                }
            })
            $("input[id=\"receivableAmount\"]").val(money)

        })
    })
    var flag =false;

    function getPre(){
        if(flag){
            var serviceorder =$("#serviceOrderId").val();
            var cust =$("#customerId").val();
            //调用后台查找预付单

            $.ajax({
                url:"${ctx}/prerecieve/tadvancesReceived/findPrePay1",
                type: "post",
                data:{serviceorder:serviceorder,cust:cust},
                dataType: "json",
                success:function(result){
                    var list =$("#paidGrid").find("tr[role='row']")
                    if(result.length>0){
                        //有几个应付详情
                        for(var k=0;k<result.length;k++){
                            //共几行
                            for(var j=1;j<list.length;j++){

                                if($(list[j]).find("input[name=\"rowNumber\"]").val()==result[k].rowNumber&&$(list[j]).find("input[name=\"expenseItem\"]").val()==result[k].advancesReceivedType){
                                    //$(list[j]).find("input[name=\"prepaymentBalance\"]").val(result[k].paymentAmountEstimated);
                                    if($(list[j]).find("td[aria-describedby=\"paidGrid_advancesReceivedCode\"]").find("select[role=\"select\"]").find("option").length==0){
                                        $(list[j]).find("td[aria-describedby=\"paidGrid_advancesReceivedCode\"]").find("select[role=\"select\"]").append("<option selected></option>");
                                    }
                                    $(list[j]).find("td[aria-describedby=\"paidGrid_advancesReceivedCode\"]").find("select[role=\"select\"]").append("<option value="+result[k].advancesReceivedCode+">"+result[k].advancesReceivedCode+"</option>>");
                                    //val(result[k].prepaymentCode);
                                }
                            }
                        }
                    }
                }});
        }else{
            for(var j=0;j<$("#paidGrid").find("tr[role='row']").length;j++){

                $($("#paidGrid").find("tr[role='row']")[j]).find("td[aria-describedby=\"paidGrid_advancesReceivedCode\"]").find("select").html("");
                $($("#paidGrid").find("tr[role='row']")[j]).find("td[aria-describedby=\"paidGrid_advancesReceivedCode\"]").find("select").append("<option selected></option>");
                $($("#paidGrid").find("tr[role='row']")[j]).find("input[name=\"receivedBalance\"]").val("");

            }
        }
    }
    $(function () {
        $('#replaceFile1').on('ifClicked', function(){
            flag=!flag;
            if(flag){
                var serviceorder =$("#serviceOrderId").val();
                var cust =$("#customerId").val();

                $.ajax({
                    url:"${ctx}/prepay/tprepayment/findPrePay1",
                    type: "post",
                    data:{serviceorder:serviceorder,cust:cust},
                    dataType: "json",
                    success:function(result){

                        var list =$("#paidGrid").find("tr[role='row']")

                        if(result.length>0){
                            //有几个应付详情
                            for(var k=0;k<result.length;k++){
                                //共几行
                                for(var j=1;j<list.length;j++){

                                    if($(list[j]).find("input[name=\"rowNumber\"]").val()==result[k].rowNumber&&$(list[j]).find("input[name=\"expenseItem\"]").val()==result[k].advancesReceivedType){
                                        if($(list[j]).find("td[aria-describedby=\"paidGrid_advancesReceivedCode\"]").find("select[role=\"select\"]").find("option").length==0){
                                            $(list[j]).find("td[aria-describedby=\"paidGrid_advancesReceivedCode\"]").find("select[role=\"select\"]").append("<option selected></option>");
                                        }
                                        $(list[j]).find("td[aria-describedby=\"paidGrid_advancesReceivedCode\"]").find("select[role=\"select\"]").append("<option value="+result[k].advancesReceivedCode+">"+result[k].advancesReceivedCode+"</option>>");

                                    }
                                }
                            }
                        }
                    }});
            }else{
                for(var j=0;j<$("#paidGrid").find("tr[role='row']").length;j++){

                    $($("#paidGrid").find("tr[role='row']")[j]).find("td[aria-describedby=\"paidGrid_advancesReceivedCode\"]").find("select").html("");
                    $($("#paidGrid").find("tr[role='row']")[j]).find("td[aria-describedby=\"paidGrid_advancesReceivedCode\"]").find("select").append("<option selected></option>");
                    $($("#paidGrid").find("tr[role='row']")[j]).find("input[name=\"receivedBalance\"]").val("");

                }
            }
        });
    })

    $(function () {
        $("#btnSubmit").click(function () {
            var list = $("input[name=\"actualArAmount\"]")
            var flag1 =false

            list.each(function () {
                if($(this).val()!=""&&$(this).val()!=null){
                    flag1 =true
                }
            })

            if(flag==false){
                if($("#receivableBank").val()==null||$("#receivableBank").val()==""){
                    js.showMessage("银行不能为空");
                    return false;
                }
                if(flag1==false||list.length<1){
                    js.showMessage("至少需添加一个实收");
                    return false;
                }
            }else if(flag==true){

                if(flag1==false||list.length<1){
                    js.showMessage("至少需添加一个实收");
                    return false;
                }
            }
        })
    })
</script>